<template>
   <div class="app-container">
      <h4 class="form-header h4">基本信息</h4>
      <el-form :model="form" label-width="80px">
         <el-row>
            <el-col :span="8" :offset="2">
               <el-form-item label="用户昵称" prop="nickName">
                  <el-input v-model="form.nickName" disabled />
               </el-form-item>
            </el-col>
            <el-col :span="8" :offset="2">
               <el-form-item label="登录账号" prop="name">
                  <el-input v-model="form.name" disabled />
               </el-form-item>
            </el-col>
         </el-row>
      </el-form>

      <h4 class="form-header h4">角色信息</h4>
      <el-row :gutter="10" class="mb8">
         <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd"
               v-hasPermi="['system:user:add']">新增</el-button>
         </el-col>
         <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete"  @click="handleDelete"
               v-hasPermi="['system:user:remove']">删除</el-button>
         </el-col>
         <!-- <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" :columns="columns"></right-toolbar> -->
      </el-row>
      <el-table v-loading="loading" :row-key="getRowKey" @row-click="(row) => clickRow(row, 'auth')" ref="roleRef"
         @selection-change="(selection) => handleSelectionChange(selection, 'auth')"
         :data="roles.slice((pageNum - 1) * pageSize, pageNum * pageSize)">
         <el-table-column label="序号" width="55" type="index" align="center">
            <template #default="scope">
               <span>{{ (pageNum - 1) * pageSize + scope.$index + 1 }}</span>
            </template>
         </el-table-column>
         <el-table-column type="selection" :reserve-selection="true" width="55"></el-table-column>
         <el-table-column label="角色编号" align="center" prop="code" />
         <el-table-column label="角色名称" align="center" prop="name" />
         <el-table-column label="权限字符" align="center" prop="roleKey" />
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="pageNum" v-model:limit="pageSize" />

      <el-form label-width="100px">
         <div style="text-align: center; margin-left: -120px; margin-top: 30px">
            <!-- <el-button type="primary" @click="submitForm()">提交</el-button> -->
            <el-button @click="close()">返回</el-button>
         </div>
      </el-form>

      <el-dialog title="分配角色" v-model="dialogVisible" width="600px" append-to-body>
         <!-- 表格数据 -->
         <el-table ref="unAuthRoleRef" v-loading="loading" :row-key="getRowKey"
            @row-click="(row) => clickRow(row, 'unaAuth')" :data="unAuthRoleList"
            @selection-change="(selection) => handleSelectionChange(selection, 'unAuth')">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="角色编号" prop="code" width="120" />
            <el-table-column label="角色名称" prop="name" :show-overflow-tooltip="true" width="150" />
            <el-table-column label="权限字符" prop="roleKey" :show-overflow-tooltip="true" width="150" />
         </el-table>
         <template #footer>
            <div class="dialog-footer">
               <el-button type="primary" @click="submitForm()">确 定</el-button>
               <el-button @click="dialogVisible = false">取 消</el-button>
            </div>
         </template>
      </el-dialog>
   </div>
</template>

<script setup name="AuthRole">
import { getAuthRole, getUnAuthRole, delAuthRole, updateAuthRole } from "@/api/system/user";

const route = useRoute();
const { proxy } = getCurrentInstance();

const loading = ref(true);
const total = ref(0);
const pageNum = ref(1);
const pageSize = ref(10);
const roleIds = ref([]);
const roles = ref([]);
const unAuthRoleList = ref([]);


const dialogVisible = ref(false);
const authRoleIds = ref([]);


const form = ref({
   nickName: undefined,
   userName: undefined,
   userId: undefined,
});

/** 新增按钮点击事件 */
function handleAdd() {
   const userId = getUserId();
   getUnAuthRole(userId).then((response) => {
      unAuthRoleList.value = response.data;
      dialogVisible.value = true;
   });
}

function getUserId() {
   return route.params && route.params.userId;
}

/** 单击选中行数据 */
function clickRow(row, type) {
   if (type === "auth") {
      proxy.$refs["roleRef"].toggleRowSelection(row);
   } else {
      proxy.$refs["unAuthRoleRef"].toggleRowSelection(row);
   }
}

/** 多选框选中数据 */
function handleSelectionChange(selection, type) {
   if (type === "auth") {
      roleIds.value = selection.map((item) => item.id);
   } else {
      authRoleIds.value = selection.map((item) => item.id);
   }
}



/** 保存选中的数据编号 */
function getRowKey(row) {
   return row.id;
}

/** 关闭按钮 */
function close() {
   const obj = { path: "/system/user" };
   proxy.$tab.closeOpenPage(obj);
}

/** 提交按钮 */
async function submitForm() {
   const userId = getUserId();
   const rIds = authRoleIds.value.join(",");
   await updateAuthRole({ userId: userId, roleIds: rIds }).then((response) => {
      proxy.$modal.msgSuccess("授权成功");
      dialogVisible.value = false;
   });
   await getAuthRole(userId).then((response) => {
         form.value = response.user;
         roles.value = response.roles;
         total.value = roles.value.length;
      });

}

async function handleDelete() {
   if (roleIds.value.length === 0) {
      proxy.$modal.msgWarning("请选择要删除的角色");
      return;
   }
   try {
      const userId = getUserId();
      const rIds = roles.value
         .filter(role => !roleIds.value.includes(role.id))
         .map(role => role.id).join(",");
      console.log(rIds);
      await delAuthRole({ userId: userId, roleIds: rIds }).then((response) => {
         proxy.$modal.msgSuccess("删除成功");
      });
      await getAuthRole(userId).then((response) => {
         form.value = response.user;
         roles.value = response.roles;
         total.value = roles.value.length;
          nextTick(() => {
             if (proxy.$refs["roleRef"]) {
            proxy.$refs["roleRef"].clearSelection();
         }
          });
      });

   } catch (error) {
      console.log("删除失败");
   }
}

(() => {
   const userId = getUserId();
   if (userId) {
      loading.value = true;
      getAuthRole(userId).then((response) => {
         form.value = response.user;
         roles.value = response.roles;
         total.value = roles.value.length;
         loading.value = false;
      });
   }
})();
</script>
